#!/usr/bin/python
# coding:utf-8

import os
import win32api, win32con, win32gui
from urllib import request
from PIL import Image


def get_bing_wallpaper(save_dir=''):
    '''
    获得 bing 的壁纸
    :param save_dir: 保存路径
    :return: 壁纸的完整路径
    '''
    print('get wallpaper info.')
    url = 'http://cn.bing.com'
    res = request.urlopen(url)
    data = res.read()
    res.close()
    data = data.decode('utf-8',errors='ignore')

    # get image url
    url_pre = 'g_img={url: \"'
    url_start = data.find(url_pre) + len(url_pre)
    url_end = data.find('\"', url_start)
    img_url = url + data[url_start:url_end]

    # get image name
    name_pre = '<a id=\"sh_cp\" class=\"sc_light\" title=\"'
    name_start = data.find(name_pre) + len(name_pre)
    name_end = data.find('\"', name_start)
    img_name = data[name_start:name_end] + '.jpg'
    img_name = img_name.replace('<', ' ').replace('>', ' ').replace('|', ' ')\
                .replace(':', ' ').replace('\"', ' ').replace('*', ' ').replace('?', ' ')\
                .replace('/', ' ').replace('\\', ' ')

    if save_dir is None or 0 == len(save_dir):
        save_dir = 'C:/Users/Public/Pictures/wallpaper/'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    full_path = save_dir + img_name
    if not os.path.exists(full_path):
        print('download wallpaper.')
        request.urlretrieve(img_url, full_path)
    print('download wallpaper complete.')
    return full_path


def set_wallpaper_from_bmp(bmp_path):
    # 打开指定注册表路径
    reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
    # 最后的参数: 2拉伸,0居中,6适应,10填充,0平铺
    win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
    # 最后的参数: 1表示平铺,拉伸居中等都是0
    win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    # 刷新桌面
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp_path, win32con.SPIF_SENDWININICHANGE)


def set_wallpaper(img_path):
    # 把图片格式统一转换成bmp格式,并放在源图片的同一目录
    img_dir = os.path.dirname(img_path)
    bmpImage = Image.open(img_path)
    new_bmp_path = os.path.join(img_dir, 'wallpaper.bmp')
    bmpImage.save(new_bmp_path, "BMP")
    set_wallpaper_from_bmp(new_bmp_path)


if __name__ == '__main__':
    wallpaper = get_bing_wallpaper()
    if wallpaper:
        set_wallpaper(wallpaper)